package cn.slipi.admin.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * TODO: 请添加描述
 *
 * @author lee
 * @date 2019-03-20
 * @since 1.0.0
 */
public class EncryptUtil {

    private final static Logger LOG = LoggerFactory.getLogger(EncryptUtil.class);


    /**
     * 获取MD5加密后的字符串
     *
     * @param str 明文
     * @return 加密后的字符串
     * @throws Exception
     */
    public static String getMD5(String str) {
        /** 创建MD5加密对象 */
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            LOG.error("java 生成 php md5 加密失败！");
            e.printStackTrace();
        }
        /** 进行加密 */
        md5.update(str.getBytes());
        /** 获取加密后的字节数组 */
        byte[] md5Bytes = md5.digest();
        String res = "";
        for (int i = 0; i < md5Bytes.length; i++) {
            int temp = md5Bytes[i] & 0xFF;
            // 转化成十六进制不够两位，前面加零
            if (temp <= 0XF) {
                res += "0";
            }
            res += Integer.toHexString(temp);
        }
        return res;
    }
}
